package org.luxor.commons.schedule.utils;

import org.luxor.commons.core.utils.SpringContextUtils;
import org.luxor.commons.core.utils.StringUtils;
import org.luxor.commons.schedule.constant.ScheduleLogStatus;
import org.luxor.commons.schedule.entity.ScheduleJobEntity;
import org.luxor.commons.schedule.entity.ScheduleJobLogEntity;
import org.luxor.commons.schedule.service.IScheduleJobLogService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 定时任务
 *
 * @author Mark sunlightcs@gmail.com
 */
public class ScheduleJob extends QuartzJobBean {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap().get(ScheduleJobEntity.JOB_PARAM_KEY);

        //数据库保存执行记录
        ScheduleJobLogEntity log = new ScheduleJobLogEntity();
        log.setJobId(scheduleJob.getJobId());
        log.setBeanName(scheduleJob.getBeanName());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(new Date());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        //获取spring bean
        IScheduleJobLogService scheduleJobLogService = null;
        try {
            scheduleJobLogService = SpringContextUtils.getBean(IScheduleJobLogService.class);
            //执行任务
            logger.debug("任务准备执行，任务ID：" + scheduleJob.getJobId());

            Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            method.invoke(target, scheduleJob.getParams());

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes(times);
            //任务状态    0：成功    1：失败
            log.setStatus(ScheduleLogStatus.SUCCEED.getValue());

            logger.debug("任务执行完毕，任务ID：" + scheduleJob.getJobId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            logger.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes(times);
            //任务状态    0：成功    1：失败
            log.setStatus(ScheduleLogStatus.FAILURE.getValue());
            log.setError(StringUtils.substring(e.toString(), 0, 2000));
        } finally {
            if (scheduleJobLogService != null) {
                scheduleJobLogService.saveLog(log);
            }
        }
    }
}
